<template>
  <div class="chat-container">
    <div class="messages" ref="messagesRef">
      <div v-for="(msg, index) in messages" :key="index" 
           :class="['message', msg.role]">
        <div class="bubble">
          <span v-if="msg.role === 'ai'">🤖</span>
          <pre v-if="msg.isCode">{{ msg.content }}</pre>
          <span v-else>{{ msg.content }}</span>
          <div v-if="msg.loading" class="loading-dots">
            <span>.</span><span>.</span><span>.</span>
          </div>
        </div>
        <span class="time">{{ msg.time }}</span>
      </div>
    </div>

    <div class="input-area">
      <textarea
        v-model="inputText"
        @keydown.enter.prevent="sendMessage"
        placeholder="输入消息..."
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading || !inputText.trim()">
        {{ isLoading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import axios from 'axios';

// 思知API配置
const API_URL = 'https://api.sizhi.com/chat';
const API_KEY = '08ed4648ac5a4b44bff20659112ef07f';

// 响应式数据
const messages = ref(JSON.parse(localStorage.getItem('chat_history')) || []);
const inputText = ref('');
const isLoading = ref(false);
const messagesRef = ref(null);

// 自动滚动优化（修复点1）
const scrollToBottom = async () => {
  await nextTick();
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight + 100;
  }
};

// 消息发送逻辑重构（修复点2）
const sendMessage = async () => {
  if (!inputText.value.trim() || isLoading.value) return;
  
  try {
    isLoading.value = true;
    
    // 添加用户消息
    const userMsg = {
      role: 'user',
      content: inputText.value,
      time: new Date().toLocaleTimeString(),
      loading: false
    };
    messages.value.push(userMsg);
    
    // 添加AI加载状态
    const aiMsg = { 
      role: 'ai', 
      content: '', 
      time: '', 
      loading: true,
      isCode: false
    };
    messages.value.push(aiMsg);
    
    const userMessage = inputText.value;
    inputText.value = '';
    
    await scrollToBottom(); // 确保DOM更新

    // API请求优化（修复点3）
    const response = await axios.get(API_URL, {
      params: {
        appid: API_KEY,
        userid: 'vue3_chat_user',
        spoken: userMessage
      },
      timeout: 10000 // 添加超时处理
    });

    // 更新AI消息
    const rawContent = response.data.data.info.text;
    const lastAiMsg = messages.value[messages.value.length - 1];
    lastAiMsg.content = rawContent.replace(/```/g, '');
    lastAiMsg.time = new Date().toLocaleTimeString();
    lastAiMsg.isCode = rawContent.includes('```');
    
  } catch (error) {
    console.error('API请求失败:', error);
    messages.value.push({
      role: 'system',
      content: error.response?.data?.message || '服务暂时不可用，请稍后重试',
      time: new Date().toLocaleTimeString()
    });
  } finally {
    isLoading.value = false;
    const lastAiMsg = messages.value[messages.value.length - 1];
    if (lastAiMsg) lastAiMsg.loading = false;
    localStorage.setItem('chat_history', JSON.stringify(messages.value));
    await scrollToBottom();
  }
};

// 初始化滚动
onMounted(() => {
  scrollToBottom();
  // 监听消息变化自动滚动（新增修复点4）
  watch(() => messages.value, scrollToBottom, { deep: true });
});
</script>
<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background: #f5f5f5;
  border-radius: 12px;
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.message {
  margin: 10px 0;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.bubble {
  max-width: 70%;
  padding: 12px 18px;
  border-radius: 15px;
  background: #343d44;
  position: relative;
  white-space: pre-wrap;
}

.message.user .bubble {
  background: #2196f3;
  color: white;
}

.loading-dots span {
  opacity: 0;
  animation: dot 1.5s infinite;
}

@keyframes dot {
  0%, 40%, 100% { opacity: 0; }
  20% { opacity: 1; }
}

.input-area {
  display: flex;
  gap: 10px;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: none;
  height: 80px;
}

button {
  padding: 12px 24px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  align-self: flex-end;
}

button:disabled {
  background: #90caf9;
  cursor: not-allowed;
}

.time {
  font-size: 12px;
  color: #666;
  align-self: flex-end;
  margin: 0 8px;
}

pre {
  background: #282c34;
  color: #abb2bf;
  padding: 10px;
  border-radius: 6px;
  overflow-x: auto;
}
</style>